package com.htu.courseService.myCourse.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.htu.courseService.common.enums.ErrorCodeEnum;
import com.htu.courseService.common.enums.RedisCachePrefix;
import com.htu.courseService.common.exception.BusinessException;
import com.htu.courseService.common.util.UserUtil;
import com.htu.courseService.courseManage.entity.Courses;
import com.htu.courseService.courseManage.vo.CourseQuery;
import com.htu.courseService.courseManage.vo.CoursesDto;
import com.htu.courseService.myCourse.dao.MyCoursesMapper;
import com.htu.courseService.myCourse.entity.UserCourses;
import com.htu.courseService.myCourse.service.MyCoursesService;
import com.htu.courseService.user.vo.UserInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class MyCoursesServiceImpl implements RedisCachePrefix, MyCoursesService {

    private final MyCoursesMapper myCoursesMapper;
    @Override
    public void studyCourses(Integer courseId) {
        UserInfo userInfo = UserUtil.getUserInfo();
        LambdaQueryWrapper<UserCourses> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCourses::getUserId,userInfo.getId());
        wrapper.eq(UserCourses::getCourseId,courseId);
        Long count = myCoursesMapper.selectCount(wrapper);
        if(count > 0){
            throw new BusinessException(ErrorCodeEnum.USER_COURSE);
        }
        UserCourses userCourses = new UserCourses();
        userCourses.setUserId(userInfo.getId());
        userCourses.setCourseId(courseId);
        userCourses.setCreatedAt(new Date());
        myCoursesMapper.insert(userCourses);
    }

    @Override
    public IPage<CoursesDto> getCoursePage(CourseQuery courseQuery) {
        IPage<Courses> page = new Page<>(courseQuery.getPageNum(),courseQuery.getPageSize());
        LambdaQueryWrapper<UserCourses> wrapper = new LambdaQueryWrapper<>();
        UserInfo userInfo = UserUtil.getUserInfo();
        wrapper.eq(UserCourses::getUserId,userInfo.getId());
        Long count = myCoursesMapper.selectCount(wrapper);

        IPage<Courses> courseList = myCoursesMapper.getMyCoursePage(page,userInfo.getId(),
                courseQuery.getCourseType());
        List<CoursesDto> coursesDtos = BeanUtil.copyToList(courseList.getRecords(), CoursesDto.class);
        IPage iPage = new Page();
        iPage.setTotal(count);
        iPage.setCurrent(courseQuery.getPageNum());
        iPage.setRecords(coursesDtos);
        iPage.setSize(coursesDtos.size());
        return iPage;
    }
}
